/**
 * des: 菜单权限控制
 * date: 2018/06/28
 * version: v1
 * author: XGP
 */
import router from '../router'
import store from '../store'
// import { Message } from 'element-ui'
import { getAllMenus } from '@/beneform4j/api/navigator'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie

NProgress.configure({ showSpinner: false })// NProgress Configuration

const whiteList = ['/login', '/authredirect']// no redirect whitelist
/**
 * 你可以使用 router.beforeEach 注册一个全局前置守卫
 * to: Route: 即将要进入的目标 路由对象
 * from: Route: 当前导航正要离开的路由
 * next: Function: 一定要调用该方法来 resolve 这个钩子
 */
router.beforeEach((to, from, next) => {
  // console.log('routerTo' + to.path)
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (store.getters.menus) {
        next()
      } else {
        getAllMenus().then(response => {
          if (response.code === '000011') { // 会话超时，退出到登录页
            store.dispatch('LogOut').then(() => {
              location.reload()
            })
            return
          }
          let data = []
          if(response.data) {
            data = response.data
          }
          store.dispatch('GetMenus', data).then((res) => {
            const roles = store.getters.roles
            // 动态生成路由
            store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表
              router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
              next({ path: to.path })
            })
          })
        }).catch(() => {
          store.dispatch('LogOut').then(() => {
            location.reload()
          })
        })
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next('/login') // 否则全部重定向到登录页
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
